// 创建右键菜单
chrome.runtime.onInstalled.addListener(() => {
    chrome.contextMenus.create({
        id: "showMe",
        title: "ShowMe -> 展示复制文本内容",
        contexts: ["selection"]
    });

    chrome.contextMenus.create({
        id: "deepThink",
        title: "DeepThink -> 将复制内容调用DeepSeek的接口",
        contexts: ["selection"]
    });
});

// 菜单点击处理
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
    if (!tab.id) return;

    // 先给目标页面注入一段极简 content-script（如果还没注入过）
    try {
        await chrome.scripting.executeScript({
            target: {tabId: tab.id},
            func: (text, action) => {
                if (action === 'showMe') {
                    alert("Selected Text: " + text);
                } else if (action === 'deepThink') {
                    // 这里可以换成真正的 fetch 调用
                    console.log("Sending to DeepSeek:", text);
                    alert("DeepSeek response: Placeholder Response");
                }
            },
            args: [info.selectionText, info.menuItemId]
        });
    } catch (e) {
        // 如果脚本已注入或页面不支持注入会走到这里，可以忽略
        console.warn(e);
    }
});

// 添加对快捷键的监听
chrome.commands.onCommand.addListener((command) => {
    if (command === 'showMe') {
        console.log("添加对快捷键的监听-showMe：", command);
        handleSelection('showMe');
    } else if (command === 'deepThink') {
        console.log("添加对快捷键的监听-deepThink：", command);
        handleSelection('deepThink');
    } else {
        console.log("添加对快捷键的监听-其他：", command);
    }
});

// 实现处理选中文本的函数
async function handleSelection(command) {
    try {
        // 获取当前活动标签页
        const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
        if (!tab || !tab.id) {
            console.warn('No active tab found');
            return;
        }

        // 执行脚本获取选中文本
        const results = await chrome.scripting.executeScript({
            target: {tabId: tab.id},
            func: () => {
                // 获取页面选中文本
                let selectedText = window.getSelection().toString().trim();
                console.log("获取页面选中文本：", selectedText);
                return selectedText;
            }
        });

        // 获取选中文本
        const selectedText = results[0]?.result;
        console.log("添加对快捷键的监听-results-selectedText：", selectedText);
        if (!selectedText) {
            console.warn('No text selected');
            // 尝试使用另一种方式获取选中文本
            try {
                const response = await chrome.tabs.sendMessage(tab.id, {action: "getSelectedText"});
                if (response && response.selectedText) {
                    processAction(command, response.selectedText);
                } else {
                    console.log("当前没有选择对应的文本");
                }
            } catch (error) {
                console.log("无法获取选中文本:", error);
            }
            return;
        }

        // 处理选中文本
        processAction(command, selectedText);
    } catch (error) {
        console.error('Error handling selection:', error);
    }
}

// 处理具体操作的函数
async function processAction(action, text) {
    console.log("处理具体操作的函数-action-text：", action, text);
    const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
    if (!tab?.id) return;

    if (action === 'showMe') {
        const message = "Selected Text: " + text;
        await chrome.scripting.executeScript({
            target: {tabId: tab.id},
            args: [message],
            func: (msg) => alert(msg)
        });
    } else if (action === 'deepThink') {
        const message = "Sending to DeepSeek: " + text;
        await chrome.scripting.executeScript({
            target: {tabId: tab.id},
            args: [message],
            func: (msg) => alert(msg)
        });
    }
}